import React, { useEffect, useRef, useState,forwardRef, useImperativeHandle}  from "react";
import { withRouter } from "react-router-dom";
import commonConfig from 'static/js/commonConfig'
import { connect } from 'react-redux'
import {publishedTest,testSubject,editPaperStatus,setRemark} from 'api/index'
import {notification,PageHeader, Button, Modal,Steps,Form,Select,Spin,Alert,Tag} from 'antd'
import {checkDraftData} from 'redux/action'
import LlxForm from 'components/LlxForm'
import AfterQuestions from "components/PageCommon/AfterQuestions";
// 查看更多弹框
import LookMore from 'components/Operations/LookMore'

const { Step } = Steps;
// 获取页面操作的权限  获取状态切换的权限 获取对应的值 
const {getPageJurisdiction,getStatusJurisdiction,statusValue,getStatusIndex} = commonConfig

// 头部
const LlxHead = forwardRef((props, ref) => {

  const {form,userName,role,examineStatus} = props

  const formItem  = form.getFieldValue()

  useImperativeHandle(ref, () => ({
    current
  }));

  const [current,setCurrent] = useState(getStatusIndex(formItem.paperStatus))

  const changeStatus = (current) => {
    const data = getStatusJurisdiction(formItem.paperStatus,formItem.createBy,formItem.rmanager,formItem.qmanager,userName,role)

    if(!data.includes(statusValue(current,formItem.paperStatus))) {
      const text = data.length?data.join(' + '):'无'
      notification.error({
        message: '不可切换该状态，你当前可选择得状态:' + text,
        description: '操作人：' + userName,
        duration:2
      });
      return
    }

    setCurrent(current)

  }
  


  return <div className="head-info">
    
    <PageHeader
      ghost={false}
      title={formItem.paperName}
      subTitle={<div>创建人 : {formItem.createBy} &nbsp;&nbsp;更新人 : {formItem.updateBy}<br></br>负责人 : {formItem.rmanager||formItem.qmanager||'无'} &nbsp;&nbsp;更新时间 : {formItem.updateTime}</div>}
      extra={!examineStatus?[
        <Button key="2" onClick={props.getMore}>更多信息</Button>,
        <Button key="1" type="primary" onClick={props.preservationData}>
          保存
        </Button>,
      ]:[<Button key="2" onClick={props.getMore}>更多信息</Button>]}
    >
             {
       examineStatus?<div className="info-status">
         {form.getFieldValue().upperLower===1010?<Tag color="success">发布状态</Tag>:(form.getFieldValue().upperLower===1000?<Tag color="error">已下架</Tag>:<Tag color="error">未知</Tag>)}
       </div>:''
    }
    {
       !examineStatus?<div className="head-status">
        {
          ['N','R','Q'].includes(formItem.paperStatus)?(
           <Steps style={{width:'400px',marginTop:'22px'}}  current={current} onChange={changeStatus}>
           <Step title="N" />
           <Step title="R" />
           <Step title="Q" />
           <Step title="P" />
         </Steps>
          ):(
           <Steps style={{width:'400px',marginTop:'22px'}}  current={current} onChange={changeStatus}>
           <Step title="PN" />
           <Step title="PR" />
           <Step title="PQ" />
           <Step title="P" />
         </Steps>
          )
        }
       </div>:''
    }
       
    
    </PageHeader>
  </div>
})

// 试卷详情
const PaperMain = (props) => {
const {disabled,form} = props
  return <div  className='info-main'>
     <AfterQuestions  disabled={disabled} type={form.getFieldValue().type===1?'TEST':'PAPER'} globalType={3} id={form.getFieldValue().id}></AfterQuestions>
  </div>
}
// 保存数据
const DataDialog  = (props) => {
const {isModalVisible, setIsModalVisible,form,changeStatus,UserSpecies,userName,disabled,QandPQ} = props
const value = statusValue(changeStatus,form.getFieldValue().paperStatus) //修改的状态
const manager = value==='Q'||value==='PQ'?QandPQ:UserSpecies
const [formItem] = Form.useForm();//试卷详情
const item = ['N','PN','P'].includes(value)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]
// 返回
 const handleCancel = () => {
    setIsModalVisible(false);
 };
//  确认修改
 const handleOk = () => {
  formItem.validateFields().then(async()=>{
  //  1更改状态
  await editPaperStatus({
    id: form.getFieldValue().id,
    paperStatus: value,
    qmanager: value==='Q'||value==='PQ'?formItem.getFieldValue().manager:'',
    rmanager: value==='R'||value==='PR'?formItem.getFieldValue().manager:'',
  })
   
  // 留言
  await setRemark({
    manager: formItem.getFieldValue().manager||'',
    dataId: form.getFieldValue().id,
    type: 'PAPER',
    remark: formItem.getFieldValue().remark,
    statusNow: form.getFieldValue().paperStatus,
    statusNext: value
  })

  //  2修改数据
   if(!disabled){
     

    notification.success({
      message: '保存成功',
      description: '操作人：' + userName,
      duration:1.5
    });
  
    props.getPaperInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   } else {

    notification.success({
      message: '保存成功',
      description: '操作人：' + userName,
      duration:1.5
    });

    props.getPaperInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   }
  })
 }

return   <>
<Modal onOk={handleOk}  width={600} title="保存数据" visible={isModalVisible}  onCancel={handleCancel}>
      <Alert className="edit-alert" message={'你确定要修改状态至' + value + '吗？'} type="success" />

     <LlxForm form={formItem} labelCol={3} formItem={item} />
 </Modal>
</>
}


function PaperInfo(props) {

  const {examineStatus} = props
  const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
  const [isModalVisibleData,setIsModalVisibleData] = useState(false)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(true)
  const id = commonConfig.getUrlParams(props).id
  const [form] = Form.useForm();//试卷详情
  const head = useRef()
  const [preservationJurisdiction,setPreservationJurisdiction] = useState({})
  // 1.获取数据
  useEffect(()=>{
    getPaperInfoFn()
  }, [examineStatus])// eslint-disable-line react-hooks/exhaustive-deps


  // 2.查看更多
  const getMore = () => {
    setIsModalVisibleMore(true)
  }
  // 3.保存数据
  const preservationData = () => {
   const value = statusValue(head.current.current,form.getFieldValue().paperStatus)
   if(!getStatusJurisdiction(preservationJurisdiction[0],preservationJurisdiction[1],preservationJurisdiction[2],preservationJurisdiction[3],preservationJurisdiction[4],preservationJurisdiction[5]).includes(value)) {
    notification.error({
      message: '该数据你无法保存，请联系管理员',
      description: '操作人：' + props.userInfo.user.userName,
      duration:2
    });
    return
   }
  
  // 打开弹框 输入备注 修改状态 修改数据
  setIsModalVisibleData(true)


  }
  // 4.更新数据
  const getPaperInfoFn = async () => {
    if(examineStatus){
      const res = await publishedTest(id)
      if(!res.result.id){
        notification.error({
          message: '该试卷未发布过',
          duration:1.5
        });
        props.checkDraftDataBtn()
        setLoading(false)
        return
      }
      form.setFieldsValue(res.result)
      setDisabled(true)
  
      setLoading(false)
    } else {
      const res = await testSubject(id)
      form.setFieldsValue(res.result)
      setDisabled(!getPageJurisdiction(res.result.paperStatus,res.result.createBy,props.userInfo.user.userName))

      setPreservationJurisdiction([res.result.paperStatus,res.result.createBy,res.result.rmanager,res.result.qmanager,props.userInfo.user.userName,props.userInfo.roles.map(i => i.id).includes(7)])
     
      setLoading(false)
    }
  }

  return <div className="app-content-info animate__animated animate__fadeIn">
  {
    !loading?(
      <>
      <LlxHead  examineStatus={examineStatus}  ref={head} preservationJurisdiction={preservationJurisdiction}  preservationData={preservationData} userName={props.userInfo.user.userName} role={props.userInfo.roles.map(i => i.id).includes(7)} form={form} getMore={getMore}></LlxHead>
       
       {/* 查看更多信息 */}
       <LookMore  type={'PAPER'}  preservationJurisdiction={preservationJurisdiction}  isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       {/* 保存数据 */}
       <DataDialog getPaperInfoFn={getPaperInfoFn} disabled={disabled} form={form} QandPQ={props.dictionaries.QandPQ} UserSpecies={props.dictionaries.UserSpecies} userName={props.userInfo.user.userName} status={form} changeStatus={head.current?.current}   id={id} isModalVisible={isModalVisibleData} setIsModalVisible={setIsModalVisibleData} ></DataDialog>
       
       {/* 主要内容区域 */}
       {/* 1.草稿可编辑 */}
       <PaperMain getPaperInfoFn={getPaperInfoFn} form={form} dictionaries={props.dictionaries} disabled={disabled}></PaperMain>
      </>
    ):<Spin className="info-loading" tip="Loading..."></Spin>
  }
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkDraftDataBtn: () => dispatch(checkDraftData())
  }
}

export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(PaperInfo))